from config import *
import urllib2
from datetime import datetime
from datetime import date
from ping import ping
class hostfileManager:
    def changeHosts(self):
        content=''
        for k,v in filelist.iteritems():
            f=None
            try:
                f=open(v)
                content+=f.read()
                content+='\n\n'
            except IOError as ioerror:
                self.logerror(ioerror.strerror,v)
            except Exception as exception:
                self.logerror(exception,v)
            finally:
                if f is not None:
                    f.close()


        for k,v in urllist.iteritems():
            urlf=None
            try:
                urlf=urllib2.urlopen(v)
                content+=urlf.read()
                content+='\n\n'
            except ValueError as valueError:
                self.logerror(valueError.message,v)
            except urllib2.URLError as urlerror:
                self.logerror(urlerror,v)
            except urllib2.HTTPError as httpError:
                self.logerror(httpError,v)
            except Exception as exception:
                self.logerror(exception,v)
            finally:
                if urlf is not None:
                    urlf.close()

        if autoping==1:
            ip=ping('www.g.cn')
            for k,v in autopinglist.iteritems():
                domainnames=None
                try:
                    domainnames = open(v)
                    for line in domainnames:
                        content+=ip+' '+line+'\n'
                except Exception as exception:
                    self.logerror(exception,v)
                finally:
                    if domainnames is not None:
                        domainnames.close()

                

        with open('c:/windows/system32/drivers/etc/hosts','w') as hostfile:
            hostfile.write(content)
        hostfile.close()

    def logerror(self,message,filePath):
        with open('error.log','a') as f:
            f.write('time:{0},error:{1}:{2}\n\n'.format(datetime.today(),message,filePath))   


if __name__=='__main__':
    hm=hostfileManager()
    hm.changeHosts()




